package dao

import (
	"github.com/go-xorm/xorm"
	"log"
	"lottery/models"
)

type EventDao struct {
	engine *xorm.Engine
}

func NewEventDao(engine *xorm.Engine) *EventDao {
	return &EventDao{engine: engine}
}

func (d *EventDao) Get(id int) (has bool, data *models.TbEvent) {
	data = &models.TbEvent{Id: id}
	has, err := d.engine.Get(data)
	if has && err == nil {
		return
	} else {
		data.Id = 0
		return
	}
}

func (d *EventDao) GetAll() []models.TbEvent {
	dataList := make([]models.TbEvent, 0)
	err := d.engine.Find(&dataList)
	if err != nil {
		log.Println("event_dao.GetAll() failed, err=", err)
	}
	return dataList
}

func (d *EventDao) GetByUser(userId int) []models.TbEvent {
	dataList := make([]models.TbEvent, 0)
	err := d.engine.
		Where("user_id=?", userId).
		And("status <> -1").
		Desc("id").
		Find(&dataList)
	if err != nil {
		log.Println("event_dao.GetByUser() failed, err=", err)
	}
	return dataList
}

func (d *EventDao) Update(data *models.TbEvent, columns []string) error {
	_, err := d.engine.Id(data.Id).MustCols(columns...).Update(data)
	return err
}

func (d *EventDao) Create(data *models.TbEvent) error {
	_, err := d.engine.Insert(data)
	return err
}
